<template>
  <el-container>
    <el-header height="60">
      <el-button type="primary" @click="showAddDialog">添加班级</el-button>
    </el-header>

    <el-main>
      <el-card>
        <el-table v-loading="loading" :data="classList" border>
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="className" label="班级名称"></el-table-column>
          <el-table-column prop="description" label="班级描述"></el-table-column>
          <el-table-column prop="createTime" label="创建时间"></el-table-column>
          <el-table-column label="状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                {{ scope.row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
<!--              <el-button type="success" size="mini" @click="goToStudentManage(scope.row)">学生管理</el-button>-->
              <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNo"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-card>
    </el-main>

    <!-- 添加/编辑班级对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="classForm" :rules="rules" ref="classForm" label-width="100px">
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="classForm.className"></el-input>
        </el-form-item>
        <el-form-item label="班主任" prop="teacherId">
          <el-select v-model="classForm.teacherId" filterable placeholder="请选择班主任">
            <el-option
              v-for="item in teacherList"
              :key="item.id"
              :label="item.trueName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级描述" prop="description">
          <el-input type="textarea" v-model="classForm.description"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="classForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import classApi from '@/api/class'
import user from '@/api/user'

export default {
  name: 'ClassManage',
  data() {
    return {
      loading: false,
      classList: [],
      teacherList: [], // 教师列表
      dialogVisible: false,
      dialogTitle: '添加班级',
      // 查询参数
      queryInfo: {
        pageNo: 1,
        pageSize: 10,
        className: '',
        teacherId: ''
      },
      total: 0, // 总记录数
      classForm: {
        className: '',
        teacherId: null,
        description: '',
        status: 1
      },
      rules: {
        className: [
          { required: true, message: '请输入班级名称', trigger: 'blur' }
        ],
        teacherId: [
          { required: true, message: '请选择班主任', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入班级描述', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getTeacherList()
    this.getClassList()
  },
  methods: {
    // 获取教师列表
    async getTeacherList() {
      try {
        const resp = await user.getUserInfo2({
          pageNo: 1,
          roleId: 2, // 教师角色ID
          pageSize: 999
        })
        if (resp.code === 200) {
          this.teacherList = resp.data.data
        }
      } catch (error) {
        console.error('获取教师列表失败:', error)
      }
    },
    // 获取班级列表
    async getClassList() {
      this.loading = true
      try {
        const resp = await classApi.getClassList(this.queryInfo)
        if (resp.code === 200) {
          this.classList = resp.data.data
          this.total = resp.data.total
        }
      } catch (error) {
        console.error('获取班级列表失败:', error)
      }
      this.loading = false
    },
    // 监听每页显示数量变化
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getClassList()
    },
    // 监听页码变化
    handleCurrentChange(newPage) {
      this.queryInfo.pageNo = newPage
      this.getClassList()
    },
    // 显示添加对话框
    showAddDialog() {
      this.dialogTitle = '添加班级'
      this.classForm = {
        className: '',
        teacherId: null,
        description: '',
        status: 1
      }
      this.dialogVisible = true
    },
    // 显示编辑对话框
    showEditDialog(row) {
      this.dialogTitle = '编辑班级'
      this.classForm = { ...row }
      this.dialogVisible = true
    },
    // 提交表单
    handleSubmit() {
      this.$refs.classForm.validate(async (valid) => {
        if (valid) {
          try {
            if (this.dialogTitle === '添加班级'){
              const resp = await classApi.saveClass(this.classForm)
              if (resp.code === 200) {
                this.$message.success('保存成功')
                this.dialogVisible = false
                this.getClassList()
              }
            }
            if (this.dialogTitle === '编辑班级'){
              const resp = await classApi.updateClass(this.classForm)
              if (resp.code === 200) {
                this.$message.success('保存成功')
                this.dialogVisible = false
                this.getClassList()
              }
            }

          } catch (error) {
            console.error('保存班级失败:', error)
          }
        }
      })
    },
    // 删除班级
    handleDelete(row) {
      this.$confirm('确认删除该班级吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          const resp = await classApi.deleteClass(row.id)
          if (resp.code === 200) {
            this.$message.success('删除成功')
            this.getClassList()
          }
        } catch (error) {
          console.error('删除班级失败:', error)
        }
      }).catch(() => {})
    },
    // 跳转到学生管理页面
    goToStudentManage(row) {
      this.$router.push(`/classStudent/${row.id}`)
    }
  }
}
</script>

<style scoped>
.el-container {
  height: 100%;
}
.el-header {
  padding: 20px;
}
.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
